package com.service.user;

import com.common.PojoUtil;
import com.common.ResultUtil;
import com.entity.Manager;
import com.entity.Manager2Role;
import com.entity.OperationLog;
import com.entity.Role;
import com.facade.log.IOperationLogFacadeCUD;
import com.facade.role.IRoleFacadeR;
import com.facade.user.IManager2RoleFacadeCUD;
import com.facade.user.cud.IManagerFacadeCUD;
import com.facade.user.r.IManagerFacadeR;
import com.mapper.CustomMapper;
import com.mapper.ManagerMapper;
import com.service.CustomServiceCUD;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ManagerServiceCUD extends CustomServiceCUD<Manager> implements IManagerFacadeCUD {

    @Resource
    private ManagerMapper mapper;
    @Resource
    private IManagerFacadeR managerFacadeR;
    @Resource
    private IManager2RoleFacadeCUD manager2RoleFacadeCUD;
    @Resource
    private IRoleFacadeR roleFacadeR;
    @Resource
    private IOperationLogFacadeCUD operationLogFacadeCUD;

    @Override
    protected CustomMapper<Manager> initMapper() {
        return mapper;
    }

    @Override
    public ResultUtil addManager(Manager manager, Long[] roleIdArray, Serializable... managerId) {
        ResultUtil resultUtil = ResultUtil.newInstance();
        String name = manager.getName();
        if ("admin".equals(name)) {
            resultUtil.setStatus(ResultUtil.FAILED);
            resultUtil.setMessage("姓名不合法，admin为系统超级管理员特有名称");
            return resultUtil;
        }
        Manager _$1 = managerFacadeR.findUniqueByPropertyEqualTo("mobile", manager.getMobile());
        if (null != _$1) {
            resultUtil.setStatus(ResultUtil.PARAM_VALID_FAILED);
            return resultUtil.setMessage("手机号码已被使用");
        }

        Date now = new Date();
        manager.setCreated(now);
        manager.setPassword(DigestUtils.md5Hex(manager.getPassword()));
        if (null == manager.getSeq()) {
            manager.setSeq(0);
        }
        addSelective(manager);
        if (null != roleIdArray && roleIdArray.length > 0) {
            List<Manager2Role> manager2RoleList = new ArrayList<>();
            for (Long roleId : roleIdArray) {
                manager2RoleList.add(new Manager2Role(manager.getId(), roleId));
            }
            manager2RoleFacadeCUD.addBatch(manager2RoleList);
        }
        if (null != managerId && managerId.length > 0) {
            List<Role> roles = roleFacadeR.findByUserLink(manager.getId());
            String message = "添加用户：[" + PojoUtil.notNull(manager, "password", "id") + "，roles：";
            for (int i = 0; i < roles.size(); i++) {
                message += roles.get(i).getName();
                if (i != roles.size() - 1) {
                    message += "、";
                }
            }
            message += "]";
            operationLogFacadeCUD.addOperationLog(managerId[0], OperationLog.ADD, message);
        }
        resultUtil.setMessage("添加成功");
        return resultUtil;
    }

    @Override
    public ResultUtil modifyManager(Manager manager, Long[] roleIdArray, Serializable... managerId) {
        ResultUtil resultUtil = ResultUtil.newInstance();
        Long id = manager.getId();
        if (null != id) {
            Manager _$0 = managerFacadeR.findByPrimaryKey(id);
            if (null == _$0) {
                resultUtil.setStatus(ResultUtil.FAILED);
                resultUtil.setMessage("记录不存在或已被删除");
                return resultUtil;
            }
            Manager _$1 = managerFacadeR.findUniqueByPropertyEqualTo("mobile", manager.getMobile());
            if (null != _$1 && !_$1.getId().equals(id)) {
                resultUtil.setStatus(ResultUtil.PARAM_VALID_FAILED);
                return resultUtil.setMessage("手机号码已被使用");
            }

            String srcName = _$0.getName();
            if ("admin".equals(srcName)) {
                manager.setName(srcName);
            }
            manager.setUpdated(new Date());
            update(manager);
            List<Role> oldRoles = null;
            if (null != managerId && managerId.length > 0) {
                oldRoles = roleFacadeR.findByUserLink(id);
            }
            manager2RoleFacadeCUD.deleteByPropertyEqualTo("managerId", id);
            if (null != roleIdArray && roleIdArray.length > 0) {
                List<Manager2Role> manager2RoleList = new ArrayList<>();
                for (Long roleId : roleIdArray) {
                    manager2RoleList.add(new Manager2Role(id, roleId));
                }
                manager2RoleFacadeCUD.addBatch(manager2RoleList);
            }
            if (null != managerId && managerId.length > 0) {
                List<Role> newRoles = roleFacadeR.findByUserLink(id);
                String message = "修改用户：[" + PojoUtil.compareDifferent(_$0, manager, "password", "id", "name") + "，roles：";
                for (int i = 0; i < oldRoles.size(); i++) {
                    message += oldRoles.get(i).getName();
                    if (i != oldRoles.size() - 1) {
                        message += "、";
                    }
                }
                message += " -> ";
                for (int i = 0; i < newRoles.size(); i++) {
                    message += newRoles.get(i).getName();
                    if (i != newRoles.size() - 1) {
                        message += "、";
                    }
                }
                message += "]";
                operationLogFacadeCUD.addOperationLog(managerId[0], OperationLog.MODIFY, message);
            }
            resultUtil.setMessage("修改成功");
        }
        return resultUtil;
    }

    @Override
    public ResultUtil deleteManager(Serializable id, Serializable... managerId) {
        ResultUtil resultUtil = ResultUtil.newInstance();
        Manager manager = managerFacadeR.findByPrimaryKey(id);
        if (null == manager) {
            resultUtil.setStatus(ResultUtil.FAILED);
            resultUtil.setMessage("记录不存在或已被删除");
            return resultUtil;
        }
        String name = manager.getName();
        if ("admin".equals(name)) {
            resultUtil.setStatus(ResultUtil.FAILED);
            resultUtil.setMessage("系统超级管理员不能删除");
            return resultUtil;
        }
        manager2RoleFacadeCUD.deleteByPropertyEqualTo("managerId", id);
        deleteByPrimaryKey(id);
        if (null != managerId && managerId.length > 0) {
            String message = "删除用户：[" + PojoUtil.notNull(manager, "password", "id", "name") + "]";
            operationLogFacadeCUD.addOperationLog(managerId[0], OperationLog.DELETE, message);
        }
        resultUtil.setMessage("删除成功");
        return resultUtil;
    }

    @Override
    public ResultUtil enableManager(Serializable id, Serializable... managerId) {
        Manager manager = managerFacadeR.findByPrimaryKey(id);
        ResultUtil resultUtil = ResultUtil.newInstance();
        if (null == manager) {
            resultUtil.setStatus(ResultUtil.FAILED);
            resultUtil.setMessage("记录不存在或已被删除");
            return resultUtil;
        }
        manager.setDisabled(false);
        update(manager);
        if (null != managerId && managerId.length > 0) {
            String message = "解锁用户：[" + PojoUtil.notNull(manager, "password", "id", "name") + "]";
            operationLogFacadeCUD.addOperationLog(managerId[0], OperationLog.MODIFY, message);
        }
        resultUtil.setMessage("解锁成功");
        return resultUtil;
    }

    @Override
    public ResultUtil disableManager(Serializable id, Serializable... managerId) {
        Manager manager = managerFacadeR.findByPrimaryKey(id);
        ResultUtil resultUtil = ResultUtil.newInstance();
        if (null == manager) {
            resultUtil.setStatus(ResultUtil.FAILED);
            resultUtil.setMessage("记录不存在或已被删除");
            return resultUtil;
        }
        String name = manager.getName();
        if ("admin".equals(name)) {
            resultUtil.setStatus(ResultUtil.FAILED);
            resultUtil.setMessage("系统超级管理员不能锁定");
            return resultUtil;
        }
        manager.setDisabled(true);
        update(manager);
        if (null != managerId && managerId.length > 0) {
            String message = "锁定用户：[" + PojoUtil.notNull(manager, "password", "id", "name") + "]";
            operationLogFacadeCUD.addOperationLog(managerId[0], OperationLog.MODIFY, message);
        }
        resultUtil.setMessage("锁定成功");
        return resultUtil;
    }

    @Override
    public ResultUtil modifyPassword(Serializable id, String password, Serializable... managerId) {
        ResultUtil resultUtil = ResultUtil.newInstance();
        Manager user = managerFacadeR.findByPrimaryKey(id);
        if (StringUtils.isBlank(password)) {
            resultUtil.setStatus(ResultUtil.FAILED);
            resultUtil.setMessage("新密码不能为空");
            return resultUtil;
        }
        user.setPassword(DigestUtils.md5Hex(password));
        update(user);
        resultUtil.setMessage("新密码将在下次登录生效");
        return resultUtil;
    }
}
